package com.university.logistic.fileter;


import com.university.logistic.config.ResourceProperties;
import com.university.logistic.exception.AuthenException;
import com.university.logistic.uitl.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

@Component
@Order(0)
public class AuthenFilter implements GlobalFilter {
    @Resource
    private ResourceProperties resourceProperties;
    private AntPathMatcher pm=new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("=========进入角色过滤===========");
        //是否需要认证
        List<String> allowOrigins = resourceProperties.getAllowOrigins();
        String uri = exchange.getRequest().getPath().toString();
        System.out.println(uri);
        if(allowOrigins!=null && allowOrigins.size()>0){
            for (String allowOrigin : allowOrigins) {
                if(pm.match(allowOrigin,uri)){
                    //通过
                    return chain.filter(exchange);
                }
            }

        }
        //如果需要认证，就先判断请求是客户端发出还是管理端发出，解析token的方法两端不一样
        List<String> tokens = exchange.getRequest().getHeaders().get("token");

        System.out.println(tokens);
        //是否有token
        if(tokens == null || tokens.isEmpty()) {
            throw new AuthenException(401,"未登录");
        }
        String value = tokens.get(0);
       // System.out.println(JwtUtil.parseAdminToken(value));
        if(uri.endsWith(".api")){
            //管理端解析
            try {
                JwtUtil.parseAdminToken(value);
            }catch (Exception e){
                throw new AuthenException(401,"未登录");
            }
        }else{
            //客户端解析
            try {
                JwtUtil.parseUserToken(value);
            }catch (Exception e){
                throw new AuthenException(401,"未登录");
            }
        }
        return chain.filter(exchange);
    }
}
